package task2

import "fmt"

type ListNode struct {
	Val  int
	Next *ListNode
}

// 获取了l1 l2 length
// return l1,l2 length
func getListLength(l1 *ListNode, l2 *ListNode) (int, int) {
	var l1_length, l2_length int = 0, 0

	for temp1 := l1; temp1 != nil; temp1 = temp1.Next {
		l1_length++
	}
	for temp2 := l2; temp2 != nil; temp2 = temp2.Next {
		l2_length++
	}
	return l1_length, l2_length
}

// 短的list前边补0
func makeNewL2(l *ListNode, num int) *ListNode {
	for temp := l; ; temp = temp.Next {
		if temp.Next == nil {
			for i := 0; i < num; i++ {
				temp.Next = &ListNode{0, nil}
				temp = temp.Next
			}
			break
		}
	}
	return l
}

func printList(l1 *ListNode) {
	for temp1 := l1; temp1 != nil; temp1 = temp1.Next {
		fmt.Printf("%d->", temp1.Val)
	}
	fmt.Println("")
}
func PrintList(l1 *ListNode) {
	for temp1 := l1; temp1 != nil; temp1 = temp1.Next {
		fmt.Printf("%d->", temp1.Val)
	}
	fmt.Println("")
}
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
	printList(l1)
	printList(l2)
	l := new(ListNode)
	templist := l
	//设定l1是长一点的队列 需要把短一点的list补充0
	length1, length2 := getListLength(l1, l2)
	if length1 < length2 {
		temp := l2
		l2 = l1
		l1 = temp
		printList(l1)
		printList(l2)
		makeNewL2(l2, length2-length1)
	} else {
		makeNewL2(l2, length1-length2)
	}
	printList(l1)
	printList(l2)
	//设置低位和进位
	var low, carry, preCarry int = 0, 0, 0
	temp1 := l1
	temp2 := l2
	for temp1 != nil {
		low = (temp1.Val + temp2.Val + preCarry) % 10
		carry = (temp1.Val + temp2.Val + preCarry) / 10
		templ := &ListNode{low, nil}
		l.Next = templ
		preCarry = carry
		temp1 = temp1.Next
		temp2 = temp2.Next
		l = l.Next
	}
	if carry == 1 {
		temp := &ListNode{1, nil}
		l.Next = temp
	}
	printList(templist)
	return templist.Next
}
func main() {
	l1 := &ListNode{9, nil}
	l2 := &ListNode{9, nil}
	l1temp := l1
	l2temp := l2
	for i := 0; i < 3; i++ {
		temp := &ListNode{9, nil}
		l1temp.Next = temp
		l1temp = l1temp.Next
	}

	for i := 0; i < 7; i++ {
		temp := &ListNode{9, nil}
		l2temp.Next = temp
		l2temp = l2temp.Next
	}

	fmt.Println(getListLength(l1, l2))
	addTwoNumbers(l1, l2)
}
